package com.example.administrator.zhongyichou.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.example.administrator.zhongyichou.Bean.DiseaseInfoBean;
import com.example.administrator.zhongyichou.adapter.LaunchDiseaseGridAdapter;
import com.example.administrator.zhongyichou.adapter.LaunchDiseaseGridAdapter1;
import com.example.administrator.zhongyichou.base.BaseActivity;
import com.example.administrator.zhongyichou.Bean.BaseEventBean;
import com.example.administrator.zhongyichou.base.MyApplication;
import com.example.administrator.zhongyichou.config.Constants;
import com.example.administrator.zhongyichou.help.StringImageToList;
import com.example.administrator.zhongyichou.net.NetConfig;
import com.example.administrator.zhongyichou.net.core.RequestHttpLoader;
import com.example.administrator.zhongyichou.net.protocol.DiseaseDetailsProtocol;
import com.example.administrator.zhongyichou.view.LoadingDialog;
import com.example.administrator.zhongyichou.net.core.HttpLoader;
import com.example.administrator.zhongyichou.net.core.UploadHttpLoader;
import com.example.administrator.zhongyichou.net.listener.ResultListener;
import com.example.administrator.zhongyichou.net.protocol.GsonBaseProtocol;
import com.example.administrator.zhongyichou.net.protocol.LaunchDreamProtocol;
import com.example.administrator.zhongyichou.utils.FileUtils;
import com.example.administrator.zhongyichou.utils.ImageUtils;
import com.example.administrator.zhongyichou.utils.ToastUtil;
import com.example.administrator.zhongyichou.view.HeaderView;
import com.example.administrator.zhongyichou.view.MyGridView;
import com.example.administrator.zhongyichou.R;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.preview.ImagePreviewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.nereo.multi_image_selector.MultiImageSelector;

/**
 * Created by lichenyu on 2017/11/20.
 * 描述：梦想筹款
 */

public class LaunchDreamFundraisingActivity extends BaseActivity<DiseaseDetailsProtocol> implements LaunchDiseaseGridAdapter1.OnClickListener, AdapterView.OnItemClickListener {
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.edit_title)
    EditText editTitle;
    @BindView(R.id.edit_content)
    EditText editContent;
    @BindView(R.id.gridview)
    MyGridView gridview;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.txt_desc)
    TextView txtDesc;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.headerview)
    HeaderView headerview;
    @BindView(R.id.edit_use)
    EditText editUse;
    @BindView(R.id.edit_initiator)
    EditText editInitiator;

    private LoadingDialog loadingDialog;
    private int REQUEST_IMAGE = 10;
    private ArrayList<String> listPhoto = new ArrayList<>();
    private ArrayList<String> listPhotoUrl = new ArrayList<>();//储存网络图片集合
    private LaunchDiseaseGridAdapter1 adapter;
    private String money;
    private String use;
    private String initiator;
    private String title;
    private String content;
    private String infoID;
    private boolean isEdit;//编辑状态，true是

    @Override
    protected void init() {
        ButterKnife.bind(this);
        initHead();
        adapter = new LaunchDiseaseGridAdapter1(this, listPhoto, listPhotoUrl);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
        adapter.setOnClick(this);
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setText("正在提交");
    }

    @Override
    protected void responseData(DiseaseDetailsProtocol mGsonBaseProtocal) {
        editMoney.setText(mGsonBaseProtocal.getData().getAims_money() + "");
        editTitle.setText(mGsonBaseProtocal.getData().getInfo_title());
        editUse.setText(mGsonBaseProtocal.getData().getAmount_use());
        editContent.setText(mGsonBaseProtocal.getData().getInfo_content());
        editInitiator.setText(mGsonBaseProtocal.getData().getInfo_name());
        if (!TextUtils.isEmpty(mGsonBaseProtocal.getData().getInfo_img())) {
            List<String> list = Arrays.asList(mGsonBaseProtocal.getData().getInfo_img().split(","));
            listPhotoUrl.addAll(new ArrayList<String>(list));
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected HttpLoader initHttpLoader() {
        RequestHttpLoader requestHttpLoader = new RequestHttpLoader(DiseaseDetailsProtocol.class);
        Map<String, String> map = new HashMap<>();
        map.put("info_id", infoID);
        map.put("user_id", MyApplication.getUserID());
        requestHttpLoader.setParams(NetConfig.RELEASE_DISEASE_INFO, map);
        return requestHttpLoader;
    }

    /**
     * 根据infoID是否为空判断是不是编辑状态
     *
     * @return
     */
    @Override
    protected boolean isRequestData() {
        infoID = getIntent().getStringExtra("info_id");
        isEdit = !TextUtils.isEmpty(infoID);
        return isEdit;
    }

    @Override
    protected int initContentView() {
        return R.layout.launch_dream_fundraising_activity;
    }

    @Override
    public boolean onEventBus(BaseEventBean baseEventBean) {
        return false;
    }

    @OnClick({R.id.txt_desc, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_desc://描述
                break;
            case R.id.btn_commit:
                commit();
                break;
        }
    }

    private void commit() {
        money = editMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            ToastUtil.showToast("请填写金额");
            return;
        }
        use = editUse.getText().toString().trim();
        if (TextUtils.isEmpty(use)) {
            ToastUtil.showToast("请填写资金用途");
            return;
        }
        initiator = editInitiator.getText().toString().trim();
        if (TextUtils.isEmpty(initiator)) {
            ToastUtil.showToast("请填写发起方姓名");
            return;
        }
        title = editTitle.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            ToastUtil.showToast("请填写筹款标题");
            return;
        }
        content = editContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            ToastUtil.showToast("请填写筹款故事");
            return;
        }
        if (!checkbox.isChecked()) {
            ToastUtil.showToast("请阅读公益筹项目发起条款");
            return;
        }
        loadingDialog.show();
        compressImage();
    }

    /**
     * 压缩图片
     */
    private void compressImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<File> listFile = ImageUtils.compressImages(listPhoto);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        releaseDream(listFile);
                    }
                });
            }
        }).start();
    }

    private void releaseDream(List<File> listFile) {
        UploadHttpLoader requestHttpLoader = new UploadHttpLoader(LaunchDreamProtocol.class);
        Map<String, String> map = new HashMap<>();
        map.put("user_id", MyApplication.getUserID());
        map.put("aims_money", money);
        map.put("amount_use", use);
        map.put("info_name", initiator);
        map.put("info_title", title);
        map.put("info_content", content);
        if (isEdit) {
            map.put("info_id", infoID);
            StringBuffer sb = new StringBuffer();
            for (String s : listPhotoUrl) {
                sb.append(s + ",");
            }
            map.put("info_img", sb.toString());
        }
        requestHttpLoader.setParams(NetConfig.RAISE_DREAM, listFile, map);
        requestHttpLoader.executor(new ResultListener<LaunchDreamProtocol>() {
            @Override
            public void success(LaunchDreamProtocol mGsonBaseProtocol) {
                FileUtils.clearImage();
                loadingDialog.dismiss();
                if (!isEdit) {
                    ToastUtil.showToast("发布成功");
                    Intent intent = new Intent(LaunchDreamFundraisingActivity.this, InitiateFundraisingSuccessActivity.class);
                    startActivity(intent);
                    DiseaseInfoBean bean = new DiseaseInfoBean();
                    bean.setType(1);
                    bean.setInfoID(mGsonBaseProtocol.getData().getInfo_id());
                    EventBus.getDefault().postSticky(new BaseEventBean<>(Constants.TYPE_0, bean));
                } else {
                    ToastUtil.showToast("修改成功");
                    EventBus.getDefault().post(new BaseEventBean<>(Constants.TYPE_6));
                }
                finish();
            }

            @Override
            public void error(String mErrorProtocal) {
                FileUtils.clearImage();
                loadingDialog.dismiss();
            }

            @Override
            public void notNet() {
                FileUtils.clearImage();
                loadingDialog.dismiss();
            }

            @Override
            public void requestError() {
                FileUtils.clearImage();
                loadingDialog.dismiss();
            }
        });
    }

    private void initHead() {
        headerview.setTitle("发起梦想筹款");
        headerview.bindOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case HeaderView.LEFT:
                        finish();
                        break;
                }
            }
        });
    }

    //获取权限
    private void getPermissions() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean value) {
                        if (value) {//如果所有权限都通过
                            startCamra();
                        } else {
                            getPermissions();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //    开启相机
    private void startCamra() {
        MultiImageSelector.create(LaunchDreamFundraisingActivity.this)
                .showCamera(true) // 是否显示相机. 默认为显示
                .count(8) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
//        .single() // 单选模式
                .multi() // 多选模式, 默认模式;
                .origin(listPhoto) // 默认已选择图片. 只有在选择模式为多选时有效
                .start(LaunchDreamFundraisingActivity.this, REQUEST_IMAGE);
    }

    @Override
    public void onItemClick(int position, int type) {//删除图片
        if (type == 0) {
            listPhotoUrl.remove(position);
        } else {
            listPhoto.remove(position);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            // 获取返回的图片列表(存放的是图片路径)
            if (data != null) {
                //返回的图片路径
                listPhoto = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                adapter.setData(listPhoto);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            getPermissions();
        } else {
            List<ImageInfo> imageInfo = new ArrayList<>();
            for (int i = 0; i < listPhotoUrl.size(); i++) {
                ImageInfo info = new ImageInfo();
                info.bigImageUrl = StringImageToList.toImage(listPhotoUrl.get(i));
                info.thumbnailUrl = StringImageToList.toImage(listPhotoUrl.get(i));
                //拿到view的位置
                View imageView;
                imageView = gridview.getChildAt(position);
                info.imageViewWidth = imageView.getWidth();
                info.imageViewHeight = imageView.getHeight();
                int[] points = new int[2];
                imageView.getLocationInWindow(points);
                info.imageViewX = points[0];
                info.imageViewY = points[1] - getStatusBarHeight();
                imageInfo.add(info);
            }
            for (int i = 0; i < listPhoto.size(); i++) {
                ImageInfo info = new ImageInfo();
                info.bigImageUrl = listPhoto.get(i);
                info.thumbnailUrl = listPhoto.get(i);
                //拿到view的位置
                View imageView;
                imageView = gridview.getChildAt(position);
                info.imageViewWidth = imageView.getWidth();
                info.imageViewHeight = imageView.getHeight();
                int[] points = new int[2];
                imageView.getLocationInWindow(points);
                info.imageViewX = points[0];
                info.imageViewY = points[1] - getStatusBarHeight();
                imageInfo.add(info);
            }
            // 启动预览
            Intent intent = new Intent(this, ImagePreviewActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) imageInfo);
            bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, position - 1);
            intent.putExtras(bundle);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
    }
}
